<template>
  <el-dialog
    v-model="dialogVisible"
    :title="!dialogParam.title ? '弹出框' : dialogParam.title"
    :destroy-on-close="true"
    :before-close="handleCancel"
    class="shezhi"
  >
    <div :class="{ dialog: dialogParam.setHeight }">
      <el-row class="dialog-style">
        <el-col :span="12" class="dialog-style-left">
          <div
            class="changeBtn"
            v-if="dialogParam.switchRoles && dialogParam.switchRoles.length"
          >
            <span
              class="cTree left_t_b"
              :class="role ? 'active' : ''"
              @click="changeRole(1)"
              >{{ dialogParam.switchRoles[0] }}</span
            ><span
              class="cTree right_t_b"
              :class="role ? '' : 'active'"
              @click="changeRole(0)"
              >{{ dialogParam.switchRoles[1] }}</span
            >
          </div>
          <el-input
            v-model="filterText"
            placeholder="请输入关键字"
            v-if="role && !dialogParam.searchConpany"
          />
          <el-select
            v-if="role && dialogParam.searchConpany"
            v-model="conpanyId"
            placeholder="请输入客户"
            class="w-full"
            filterable
            remote
            :remote-method="queryCustomer"
          >
            <el-option
              v-for="item in conpanyTree"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            >
              <div>
                <span>{{ item.customerName }}</span>
                <span>({{ item.mainContactName }})</span>
              </div>
            </el-option>
          </el-select>
          <el-tree
            v-if="role && !dialogParam.searchConpany"
            ref="treeRef"
            :data="dialogObj.data"
            node-key="id"
            default-expand-all
            show-checkbox
            :check-strictly="dialogObj.checkStrictly"
            :class="dialogObj.multiple ? '' : 'customNodeClass'"
            :check-on-click-node="true"
            :filter-node-method="filterNode"
            @check-change="nodeClick"
            :default-checked-keys="dialogObj.defaultCheckedKeys"
          />
          <el-tree
            v-if="!role"
            ref="treeRefRole"
            :data="dialogObj._data"
            node-key="id"
            default-expand-all
            show-checkbox
            :check-strictly="dialogObj.checkStrictly"
            :class="dialogObj.multiple ? '' : 'customNodeClass'"
            :check-on-click-node="true"
            :filter-node-method="filterNode"
            @check-change="nodeClick"
            :default-checked-keys="dialogObj.defaultCheckedKeys"
          >
          </el-tree>
        </el-col>
        <el-col :span="12" class="dialog-style-right">
          <el-row>
            <el-col :span="18">已选</el-col>
            <el-col :span="6" class="clear" @click="handleClear">清空</el-col>
          </el-row>
          <ul class="dialog-style-list">
            <li
              v-for="item in selectData"
              :key="item.value"
              @click="handleDel(item)"
            >
              {{ item.label }}
              <span>×</span>
            </li>
          </ul>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleAffirm"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="SelectDialog">
import { ElTree } from 'element-plus'
import { getCurrentInstance, nextTick, watchEffect, watch, computed } from 'vue'
import { getListByCustomerName } from '@/api/customerManage/customerList'
const { proxy } = getCurrentInstance()
// 接受父级传递的参数
const props = defineProps({
  dialogParam: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  }
})
/**
 * 新增
 */
const role = ref(true) // TODO: 切换树
const treeRefRole = ref(null)
const conpanyTree = ref([])
const conpanyId = ref()
/**
 * 新增结束
 */
const treeRef = ref(null)
// 选中的数据
const selectData = ref([])
// 弹出框是否隐藏
const dialogVisible = ref(false)

//设置参数
const dialogObj = reactive({
  // avue-tree 的数据
  data: [], // tree的数据
  _data: [], // 另一个tree的数据 //新增
  multiple: false, //是否多选
  checkStrictly: false, //是否遵循父子不互相关联的做法，默认为 false
  // 默认设置
  defaultProps: {
    children: 'children',
    label: 'label'
  },
  defaultCheckedKeys: [] //默认选中的值key
})
// 搜索关键字
const filterText = ref('')
// 保存 selectData
const saveData = ref(null)

const emit = defineEmits(['ok', 'close'])
watch(filterText, val => {
  if (role.value) {
    return treeRef.value && !treeRef.value.filter(val)
  } else {
    return !treeRefRole.value.filter(val)
  }
})

watch(conpanyId, val => {
  if (role.value) {
    const choose = conpanyTree.value.filter(item => item.id === val)
    if (choose.length && val) {
      // if (
      //   (props.dialogParam.PartyaId && props.dialogParam.from !== 'Partya') ||
      //   (props.dialogParam.PartybId && props.dialogParam.from !== 'Partyb')
      // ) {
      //   proxy.$modal.msgWarning(
      //     '合同甲方、乙方不能同时选择内部单位或者外部客户'
      //   )
      //   conpanyId.value = null
      //   return
      // }
      selectData.value = [
        {
          id: choose[0].id,
          value: choose[0].id,
          label: choose[0].customerName
        }
      ]
    }
  }
})

watchEffect(
  () => {
    dialogVisible.value = props.dialogParam.isDialog // 表单弹出框
    dialogObj.data = props.dialogParam.data // tree的数据
    dialogObj._data = props.dialogParam._data // tree的数据
    dialogObj.multiple = props.dialogParam.multiple //是否多选
    dialogObj.defaultCheckedKeys = props.dialogParam.defaultCheckedKeys // 选中de key
    dialogObj.checkStrictly = props.dialogParam.checkStrictly //是否遵循父子不互相关联的做法
    role.value = props.dialogParam.isCustom
    conpanyId.value = null
    if (props.dialogParam.defaultCheckedKeys != undefined) {
      nextTick(() => {
        let sData
        if (role.value && treeRef.value && !dialogObj.searchConpany) {
          sData = treeRef.value.getCheckedNodes() //获取选中的值
        } else if (treeRefRole.value) {
          sData = treeRefRole.value.getCheckedNodes() //获取选中的值
        }
        if (props.dialogParam.searchConpany) {
          if (props.dialogParam.isCustom) {
            conpanyId.value = props.dialogParam.label
            selectData.value = [
              {
                label: props.dialogParam.label,
                id: props.dialogParam.defaultCheckedKeys[0],
                value: props.dialogParam.defaultCheckedKeys[0]
              }
            ]
          } else {
            let sData = treeRefRole.value.getCheckedNodes()
            selectData.value = sData
          }
          // &&
          // ((props.dialogParam.PartyaId &&
          //   props.dialogParam.from === 'Partya') ||
          //   (props.dialogParam.PartybId && props.dialogParam.from === 'Partyb'))
        } else {
          selectData.value = dialogObj.checkStrictly
            ? sData
            : (sData || []).filter(item => !item.children)
        }
      })
    }
  },
  {
    flush: 'post'
  }
)
// 过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}
// tree点击选中
const nodeClick = (data, checked) => {
  conpanyId.value = null
  if (!dialogObj.multiple) {
    if (checked) {
      dialogObj.defaultCheckedKeys = [data.id]
      if (role.value) {
        treeRef.value.setCheckedKeys([data.id])
      } else {
        treeRefRole.value.setCheckedKeys([data.id])
      }
    } else {
      if (
        dialogObj.defaultCheckedKeys &&
        dialogObj.defaultCheckedKeys[0] === data.id
      ) {
        if (role.value) {
          treeRef.value.setCheckedKeys([data.id])
        } else {
          treeRefRole.value.setCheckedKeys([data.id])
        }
      }
    }
  }
  let sData
  if (role.value) {
    sData = treeRef.value.getCheckedNodes()
  } else {
    sData = treeRefRole.value.getCheckedNodes()
  }
  selectData.value = dialogObj.checkStrictly
    ? sData
    : sData.filter(item => !item.children)
}

// 确认操作
const handleAffirm = () => {
  let sData = [...selectData.value]
  let labelData = [],
    defaultCheckedKeys = []
  sData.forEach(item => {
    labelData.push(item.label)
    defaultCheckedKeys.push(item.id)
  })

  // if (
  //   ((props.dialogParam.PartyaId && props.dialogParam.from !== 'Partya') ||
  //     (props.dialogParam.PartybId && props.dialogParam.from !== 'Partyb')) &&
  //   labelData.length &&
  //   role.value
  // ) {
  //   proxy.$modal.msgWarning('合同甲方、乙方不能同时选择内部单位或者外部客户')
  //   conpanyId.value = null
  //   return
  // }

  // if (
  //   ((props.dialogParam.PartyaIsInside &&
  //     props.dialogParam.from !== 'Partya') ||
  //     (props.dialogParam.PartybIsInside &&
  //       props.dialogParam.from !== 'Partyb')) &&
  //   labelData.length &&
  //   !role.value
  // ) {
  //   proxy.$modal.msgWarning('合同甲方、乙方不能同时选择内部单位或者外部客户')
  //   conpanyId.value = null
  //   return
  // }
  emit('ok', {
    type: props.dialogParam.type,
    selectData: sData,
    labelData: labelData, // 选中的数据label
    defaultCheckedKeys: defaultCheckedKeys, // 选中的数据id
    dialogVisible: false,
    isCustom: role.value
  })
  reset()
}
// 取消操作
const handleCancel = () => {
  reset()
  emit('close')
}
// 删除选中数据
const handleDel = val => {
  let sData = [...selectData.value]
  selectData.value = sData.filter(item => item.value != val.value)
  if (props.dialogParam.searchConpany) {
    selectData.value = sData.filter(item => item.value != val.value)
    conpanyId.value = null
  }
  if (role.value) {
    treeRef.value && treeRef.value.setCheckedNodes(selectData.value)
  } else {
    treeRefRole.value.setCheckedNodes(selectData.value)
  }
  dialogObj.defaultCheckedKeys = dialogObj.defaultCheckedKeys.map(
    item => item != val.id
  )
}
// 清空数据
const handleClear = () => {
  if (props.dialogParam.searchConpany) {
    conpanyId.value = null
  }
  if (role.value) {
    treeRef.value && treeRef.value.setCheckedKeys([])
  } else {
    treeRefRole.value.setCheckedKeys([])
  }
  selectData.value = []
  dialogObj.defaultCheckedKeys = []
}
const reset = () => {
  dialogVisible.value = false
  dialogObj.data = []
  selectData.value = []
  dialogObj.defaultCheckedKeys = []
  filterText.value = ''
}

/*
 * 新增
 */
function changeRole(flag) {
  role.value = !!flag
}

/**
 * 所属企业模糊搜索
 * @param val 当前输入的值
 */
async function queryCustomer(val) {
  let params = {
    pageSize: 9999,
    customer: val
  }
  try {
    const res = await getListByCustomerName(params)
    if (res.code === 200) {
      conpanyTree.value = res.data || []
    }
  } catch (error) {
    console.log(error)
  }
  let sData = [...selectData.value]
  let title = conpanyId.value
  handleClear()
  selectData.value = sData
  conpanyId.value = title
}
</script>
<style scoped lang="scss">
ul,
li {
  margin: 0;
  margin-block-end: 0;
  margin-block-start: 0;
}
.dialog-style {
  @apply mt--20px;
  .dialog-style-left {
    border-right: 1px solid #ccc;
    @apply pr-20px;
    .customNodeClass {
      :deep(.el-checkbox__inner) {
        @apply rounded-50;
      }
    }
  }
  .dialog-style-right {
    @apply leading-30px pl-20px  cursor-pointer;
    .clear {
      color: var(--el-color-primary);
      @apply text-right;
    }
  }
  .dialog-style-list {
    @apply mt-15px ml--40px  leading-20px;
    li {
      color: #999;
      background-color: #f5f5f5;
      @apply flex list-none pl-15px pt-5px pb-5px mb-10px rounded-35px;
      span {
        color: var(--el-color-primary);
        @apply flex-1 text-right pr-15px cursor-pointer;
      }
    }
  }
  /*
  * 新增
  */
  .changeBtn {
    border: 1px solid #ccc;
    line-height: 30px;
    margin-bottom: 15px;
    border-radius: 5px;
    .cTree {
      @apply inline-block text-center;
      width: 50%;
      color: #aaa9a9;
      cursor: pointer;
    }
    .active {
      background-color: rgb(64, 158, 255);
      color: white;
    }
    .left_t_b {
      border-top-left-radius: 5px;
      border-bottom-left-radius: 5px;
    }
    .right_t_b {
      border-top-right-radius: 5px;
      border-bottom-right-radius: 5px;
    }
  }
}
.dialog {
  height: 400px;
}
</style>
